<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("modules.contract.contract_title") }}
    </PageTitle>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="totalCount"
      @current-change="handleCurrentChange"
    >
      <el-form class="p-4" inline :model="dataForm">
        <el-form-item>
          <el-input
            ref="name"
            v-model="userName"
            clearable
            :placeholder="$t('common.customer_name')"
            @clear="clearContractName"
            @focus="openCustomerList"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="contractNum"
            clearable
            :placeholder="$t('modules.contract.contract_no')"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="status" clearable :placeholder="$t('common.status')">
            <el-option
              v-for="item in contractStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-permission="{
              permission: ['10401000.MANAGE', '10401000.QUERY', '10401000.DELETE'],
            }"
            type="primary"
            class="w-8"
            @click="getContractList"
          >
            <svg-icon icon-class="Search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            v-permission="{ permission: '10401000.MANAGE' }"
            type="primary"
            class="w-8"
            @click="() => $router.push('/service-management/contract/add')"
          >
            <svg-icon icon-class="Plus" />
          </el-button>
        </el-form-item>
        <!-- <el-button type="primary" size="small" style="margin:0px" @click="() => $router.push('/add/contract')"><i class="el-icon-plus" size="small" /></el-button> -->
      </el-form>
      <el-table v-loading="loading" :data="contractList" stripe>
        <el-table-column prop="contractNum" :label="$t('modules.contract.contract_no')">
          <template v-slot="scope">
            <div
              class="cursor-pointer"
              @click="
                () =>
                  $router.push({
                    path: '/service-management/contract/detail',
                    query: { contractUuid: scope.row.contractUuid },
                  })
              "
            >
              {{ scope.row.contractNum }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.customer_name')"
          prop="userName"
          align="center"
        >
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start" open-delay="500">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("common.customer_type") }}:
                      {{ scope.row.characterCode }} (ID: {{ scope.row.keyId }})</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.userName }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="validDate" :label="$t('common.startDate')" align="center">
          <template v-slot="scope">
            <el-tag
              size="medium"
              :type="
                scope.row.status == 0
                  ? 'danger'
                  : scope.row.isOver == 'nearly'
                  ? 'warning'
                  : scope.row.isOver == 'valid'
                  ? ''
                  : 'info'
              "
              disable-transitions
              :class="{
                tagBackground:
                  scope.row.isOver == 'valid' && scope.row.status == 1 ? true : false,
              }"
            >
              {{ scope.row.validDate }}
            </el-tag>
            <!-- <div style="background:#fef0f0;height:100%;" v-if="scope.row.isOver == 'valid'&&scope.row.status == 1">{{ scope.row.validDate }}</div> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="creUserName"
          align="center"
          :label="$t('modules.contract.creator')"
        />
        <el-table-column
          :label="$t('common.status')"
          prop="status"
          style="background-color: pink"
          align="center"
        >
          <template v-slot="scope">
            <div class="montyly-resource-settlement-tooltip">
              <el-tooltip v-if="scope.row.status == 0" placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("modules.contract.reject_time") }}:
                      {{ scope.row.invalidTime }}</span
                    ><br />
                    <span
                      >{{ $t("modules.contract.reject_person") }}:
                      {{ scope.row.invalidUserName }}</span
                    >
                  </div></template
                >
                <div>
                  <el-tag
                    size="small"
                    :type="scope.row.status == 1 ? 'success' : 'danger'"
                    disable-transitions
                  >
                    {{
                      scope.row.status == 0
                        ? $t("modules.contract.contract_status.invalid")
                        : $t("modules.contract.contract_status.valid")
                    }}
                  </el-tag>
                </div>
              </el-tooltip>
            </div>
            <el-tag
              v-if="scope.row.status == 1"
              size="small"
              :type="scope.row.status == 1 ? 'success' : 'danger'"
              disable-transitions
            >
              {{
                scope.row.status == 1
                  ? $t("modules.contract.contract_status.invalid")
                  : $t("modules.contract.contract_status.valid")
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.create_time')" prop="creDate" align="center">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span>{{ scope.row.creTime }}</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.creDate }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-dropdown>
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    @click.native="
                      () =>
                        $router.push({
                          path: '/service-management/contract/detail',
                          query: { contractUuid: scope.row.contractUuid },
                        })
                    "
                  >
                    <svg-icon icon-class="View" />
                    {{ $t("modules.contract.contract_detail") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1 && isAuth('10401000.MANAGE')"
                    @click.native="
                      () =>
                        $router.push({
                          path: '/service-management/contract/edit',
                          query: { contractUuid: scope.row.contractUuid },
                        })
                    "
                  >
                    <svg-icon icon-class="Edit" />
                    {{ $t("modules.contract.contract_edit") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="isAuth('10401000.DELETE')"
                    @click.native="ContractDelete(scope.row.contractUuid)"
                  >
                    <svg-icon icon-class="Delete" />
                    {{ $t("modules.contract.contract_delete") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1 && isAuth('10401000.MANAGE')"
                    @click.native="ContractInvalid(scope.row.contractUuid)"
                  >
                    <svg-icon icon-class="CircleClose" />
                    {{ $t("modules.contract.status_option[0].label") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 0 && isAuth('10401000.MANAGE')"
                    @click.native="ContractValid(scope.row.contractUuid)"
                  >
                    <svg-icon icon-class="CircleCheck" />
                    {{ $t("modules.contract.status_option[1].label") }}
                  </el-dropdown-item>
                </el-dropdown-menu></template
              >
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <customer-list
      ref="customerList"
      v-model="customerListVisible"
      @confirmSelect="confirmSelectCustomer"
    />
  </div>
</template>

<script>
import {
  findContract,
  invalidContract,
  deleteContract,
  validContract,
} from "@/api/contract";
import { toTime, addDiver, toTenYMD } from "@/utils/index";
import CustomerList from "@/views/service-management/components/customer-list.vue";
import { isAuth } from "@/utils";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  name: "Contract",
  components: {
    CustomerList,
    PageTitle,
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      customerListVisible: false,
      customerData: [],
      loading: false,
      totalCount: undefined,
      pageNo: 1,
      pageSize: 10,
      nameTotalCount: undefined,
      namePageNo: 1,
      namePageSize: 10,
      admin: "",
      contractData: {
        characterCode: "",
        keyId: "",
      },
      radio: "",
      contractNum: "",
      status: "",
      contractList: [],
      userName: "",
      condition: "", // 客户名称搜索内容
    };
  },
  computed: {
    contractStatusList() {
      return [
        { value: 0, label: this.$t("modules.contract.contract_status.invalid") },
        { value: 1, label: this.$t("modules.contract.contract_status.valid") },
        { value: -1, label: this.$t("modules.contract.contract_status.completed") },
      ];
    },
    settingList() {
      return {
        columns: [
          {
            title: this.$t("common.short_name"),
            code: "SHORT_NAME",
          },
          {
            title: this.$t("common.address"),
            code: "ADDRESS",
          },
          {
            title: this.$t("common.link_man"),
            code: "LINKMAN",
          },
          {
            title: this.$t("common.mobile"),
            code: "MOBILE",
          },
          {
            title: this.$t("common.email"),
            code: "EMAIL",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [],
      };
    },
  },
  mounted() {
    this.$store.commit("app/ADD_KEEP_ALIVE_LIST", "Contract");
    this.getContractList();
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "detailContract") {
      this.$store.commit("app/REMOVE_KEEP_ALIVE_LIST", "Contract");
    }
    next();
  },
  methods: {
    isAuth,
    // 加入小手状态
    cellStyle(data) {
      if (data) {
        return "cursor:pointer;";
      }
    },
    showHeader(label) {
      // 重置高度
      // this.$nextTick(() => {
      //   this.$refs.customerData.doLayout()
      // })
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    confirmSelectCustomer(selectedCustomer) {
      this.contractData.characterCode = "OPERATOR";
      this.contractData.keyId = selectedCustomer.keyId;
      this.userName = selectedCustomer.name;
      // this.customerListVisible = false;
      this.condition = "";
      // console.log(selectedCustomer)
    },
    openCustomerList() {
      this.customerListVisible = true;
      this.$nextTick(() => {
        this.$refs.customerList.openDialog();
      });
    },
    // 获取合同列表
    getContractList() {
      this.loading = true;
      const params = {
        characterCode: this.contractData.characterCode,
        keyId: this.contractData.keyId,
        contractNum: this.contractNum,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        status: this.status,
      };
      findContract(params)
        .then((res) => {
          this.totalCount = res.total;
          this.contractList = res.list;
          for (let i = 0; i < this.contractList.length; i++) {
            const endTime = parseInt(this.contractList[i].expiringDate);
            this.contractList[i].creDate = toTenYMD(
              parseInt(this.contractList[i].creTime)
            );
            this.contractList[i].creTime = toTime(parseInt(this.contractList[i].creTime));
            if (this.contractList[i].invalidUserId != null) {
              this.contractList[i].invalidUserId = this.contractList[
                i
              ].invalidUserId.toString();
            }
            if (this.contractList[i].invalidTime != null) {
              this.contractList[i].invalidTime = toTime(
                parseInt(this.contractList[i].invalidTime)
              );
            }
            this.contractList[i].effectiveDate = addDiver(
              this.contractList[i].effectiveDate
            );
            this.contractList[i].validDate = this.contractList[i].effectiveDate.join("");
            // 判断合同有效期到期时间
            const currentTime = parseInt(toTenYMD(new Date()));
            if (endTime - currentTime >= 0 && endTime - currentTime <= 90) {
              // 合同剩余不足90天就要到期了
              this.contractList[i]["isOver"] = "nearly";
            } else if (endTime - currentTime < 0) {
              // 合同已经过期了，但未失效
              this.contractList[i]["isOver"] = "overButValid";
            } else {
              // 合同还没有过期
              this.contractList[i]["isOver"] = "valid";
            }
          }
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.message);
          this.loading = false;
        });
    },
    // 处理分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getContractList();
    },
    // 取消获取的UserName
    cancelUserName() {
      this.getUserNameVisible = false;
      this.radio = "";
    },
    // 清空Customer Name
    clearContractName() {
      this.contractData.characterCode = "";
      this.contractData.keyId = "";
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.invalidCount = val.length;
    },
    // 合同一键失效
    ContractInvalid(Uuid) {
      // 加个确认
      this.$confirm(this.$t("tip_content.invalid_contract"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          invalidContract(Uuid)
            .then((res) => {
              console.log(res);
              this.getContractList();
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    // 合同一键生效
    ContractValid(Uuid) {
      // 加个确认
      this.$confirm(this.$t("tip_content.valid_contract"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          validContract(Uuid)
            .then((res) => {
              console.log(res);
              this.getContractList();
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    // 删除合同
    ContractDelete(Uuid) {
      // 加个确认
      this.$confirm(this.$t("tip_content.delete_contract"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          deleteContract(Uuid)
            .then((res) => {
              console.log(res);
              this.getContractList();
              this.$t("common.success");
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
  },
};
</script>

<style scoped>
.box {
  margin: 0.2em 0.5em;
}
.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}
.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}
.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.cell_gray {
  background-color: pink;
}

.tagBackground {
  color: black;
  background: rgba(255, 255, 255, 1);
  border-width: 0px;
}
</style>
